package com.kandinfo.base.common.util.sftp;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kandinfo.base.common.util.ApplicationContextUtil;
import com.kandinfo.base.common.util.DateUtils;
import com.kandinfo.base.common.util.StringUtil;
import com.kandinfo.base.common.util.ftp.FtpClientPoolFactory;


/**
 * Class Name: FtpUtil Description: ftp工具类
 * 
 * @author jialiangli
 */
public class FtpUtil {

    private static final Logger logger = LoggerFactory.getLogger(FtpUtil.class);

    /**
     * Description: 上传文件
     *
     * @param fileName
     * @param input
     * @param image
     * @param imagePath
     * @throws IOException
     * @throws Exception
     */
    public static String upLoad(String fileName, InputStream input, String targeDirectory, String subFolder)
            throws IOException {
        FtpClientPoolFactory pool = ApplicationContextUtil.getBean(FtpClientPoolFactory.class);
        FTPClient ftpClient = pool.getConnection();
        try {
            //设置文件类型（二进制）   
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            String date = DateUtils.format(new Date(), "yyyyMM");
            delete(fileName, targeDirectory, subFolder + "/" + date);
            changeWorkingDirectory(ftpClient, targeDirectory + subFolder);
            // 获取目录
            FTPFile[] files = ftpClient.listFiles();
            Boolean uploadRes = false;
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    // 如果文件夹中没有当前月则创建
                    String name = files[i].getName();
                    if (!name.equals(date)) {
                        ftpClient.makeDirectory(date);
                        changeWorkingDirectory(ftpClient, targeDirectory + subFolder + "/" + date);
                        uploadRes = ftpClient.storeFile(fileName, input);
                        break;
                    } else {
                        changeWorkingDirectory(ftpClient, targeDirectory + subFolder + "/" + date);
                        uploadRes = ftpClient.storeFile(fileName, input);
                        break;
                    }
                } else {
                    ftpClient.makeDirectory(date);
                    changeWorkingDirectory(ftpClient, targeDirectory + subFolder + "/" + date);
                    uploadRes = ftpClient.storeFile(fileName, input);
                    break;
                }
            }
            if(uploadRes){
                return "/" + date+"/"+fileName;
            }
        }finally {
            pool.releaseConnection(ftpClient);
        }
        return null;
    }

    public static boolean mkdir(String targeDirectory, String subFolder) {
        FtpClientPoolFactory pool = ApplicationContextUtil.getBean(FtpClientPoolFactory.class);
        FTPClient ftpClient = pool.getConnection();
        try {
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            if (StringUtil.isNotEmpty(subFolder)) {
                changeWorkingDirectory(ftpClient, targeDirectory);
                return ftpClient.makeDirectory(transcoding(subFolder));
            }
        } catch (IOException e) {
            logger.error("创建文件失败", e);
        } finally {
            pool.releaseConnection(ftpClient);
        }
        return false;
    }

    public static String transcoding(String str) throws UnsupportedEncodingException {
        return new String(str.getBytes("GBK"), "iso-8859-1");
    }

    /**
     * Description: 上传文件
     *
     * @param fileName
     * @param input
     * @param image
     * @param imagePath
     */
    public static String upLoadImage(String targeDirectory, String imagePath, String fileName, InputStream input) {
        FtpClientPoolFactory pool = ApplicationContextUtil.getBean(FtpClientPoolFactory.class);
        FTPClient ftpClient = pool.getConnection();
        SimpleDateFormat sm = new SimpleDateFormat("yyyyMM");
        String date = sm.format(new Date());
        try {
            // 设置文件类型
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            // 切换目录
            changeWorkingDirectory(ftpClient, targeDirectory + imagePath);
            // 获取目录
            FTPFile[] files = ftpClient.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    // 如果文件夹中没有当前月则创建
                    String name = files[i].getName();
                    if (!name.equals(date)) {
                        ftpClient.makeDirectory(date);
                        changeWorkingDirectory(ftpClient, targeDirectory + imagePath + "/" + date);
                        ftpClient.storeFile(fileName, input);
                        break;
                    } else {
                        changeWorkingDirectory(ftpClient, targeDirectory + imagePath + "/" + date);
                        ftpClient.storeFile(fileName, input);
                        break;
                    }
                } else {
                    ftpClient.makeDirectory(date);
                    changeWorkingDirectory(ftpClient, targeDirectory + imagePath + "/" + date);
                    ftpClient.storeFile(fileName, input);
                    break;
                }
            }

        } catch (Exception e) {
            logger.error("文件上传失败", e);
        } finally {
            pool.releaseConnection(ftpClient);
        }
        return date;
    }

    /**
     * Description: 删除文件
     *
     * @param fileName
     * @param image
     * @param imagePath
     */
    public static void delete(String fileName, String targeDirectory, String subFolder) {
        FtpClientPoolFactory pool = ApplicationContextUtil.getBean(FtpClientPoolFactory.class);
        FTPClient ftpClient = pool.getConnection();
        try {
            changeWorkingDirectory(ftpClient, targeDirectory + subFolder);
            ftpClient.deleteFile(fileName);
        } catch (Exception e) {
            logger.error("文件删除失败", e);
        } finally {
            pool.releaseConnection(ftpClient);
        }
    }

    /**
     * Description: 目录切换(备注:当部分路径不存在时进行创建)
     *
     * @param ftpClient
     * @param targetPath
     */
    private static void changeWorkingDirectory(FTPClient ftpClient, String targetPath) {
        ftpClient.enterLocalPassiveMode();
        try {
            boolean result = ftpClient.changeWorkingDirectory(targetPath);
            if (!result) {
                ftpClient.changeWorkingDirectory("/");
                String[] paths = targetPath.split("/");
                for (int i = 0; i < paths.length; i++) {
                    ftpClient.makeDirectory(paths[i]);
                    ftpClient.changeWorkingDirectory(paths[i]);
                }
                if (!ftpClient.changeWorkingDirectory(targetPath)) {
                    logger.error("调转到目标目录失败");
                    return;
                }
            }
        } catch (IOException e) {
            logger.error("调转到目标目录失败", e);
        }
        logger.debug("调转到目标目录");
    }
}
